package com.lyandwc.lw_bbs.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletResponse;
import java.io.PrintWriter;

public class ResponseUtils {
    public static void response(ServletResponse response, Object responseData) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");

            out = response.getWriter();
            out.println(JSON.toJSONString(responseData));
            out.flush();
        } catch (Exception e) {

        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static void response(ServletResponse response, int code, String msg, Object data) {
        JSONObject responseData = new JSONObject();
        responseData.put("code", code);
        responseData.put("msg", msg);
        responseData.put("data", data);
        response(response, responseData);
    }

    public static JSONObject success(Object data) {
        JSONObject responseData = new JSONObject();
        responseData.put("code", 200);
        responseData.put("msg", "成功");
        responseData.put("data", data);
        return responseData;
    }

    public static JSONObject fail(Object data) {
        JSONObject responseData = new JSONObject();
        responseData.put("code", 500);
        responseData.put("msg", "失败");
        responseData.put("data", data);
        return responseData;
    }
}
